@tool
extends EditorImportPlugin

const ANIM_TEMPLATE = {
	"idle":{"frames":1,"y_pos":0},
	"idle_left":{"frames":1,"y_pos":1},
	"idle_right":{"frames":1,"y_pos":2},
	"idle_up":{"frames":1,"y_pos":3},
	"move_down":{"frames":4,"y_pos":0},
	"move_left":{"frames":4,"y_pos":1},
	"move_right":{"frames":4,"y_pos":2},
	"move_up":{"frames":4,"y_pos":3}
}

func _get_importer_name() -> String:
	print("_get_recognized_extensions")
	return "com.npc_importer"

func _get_import_order()->int:
	return 0;

func _get_recognized_extensions() -> PackedStringArray:
	print("_get_recognized_extensions")
	return ["png"]
# 定义导入预设 不需要返回0
func _get_preset_count() -> int:
	print("_get_preset_count")
	return 0

func _get_preset_name(preset_index: int) ->String:
	return "default"

# 配置导入选项
func _get_import_options(path: String, preset_index: int) -> Array[Dictionary]:
	print("_get_import_options")
	return [{
		"name":"grid size",
		"default_value":32,
		"property_hint":PROPERTY_HINT_ENUM,
		"hint_string":"32"
	}]

func _get_visible_name() -> String:
	print("_get_visible_name")
	return "NPC动画资源"

func _get_save_extension() -> String:
	print("_get_save_extension")
	return "tres"
	
func _get_resource_type() -> String:
	print("_get_resource_type")
	return ""

func _get_option_visibility(path,option, options):
	return true
	
func _get_priority():
	return 1000  # 默认值为1，数值越高优先级越高

func _import(source_file:String,save_path:String,options:Dictionary,platform:Array,gen_files:Array)-> Error:
	print("----------------------导入开始----------------------:",source_file)
	var grid_size = options.get("grid size")
	var full_texture:Resource = load(source_file)
	if full_texture == null:
		return OK
	var image:Image = full_texture.get_image()
	var frames = SpriteFrames.new()
	
	for anim_name in ANIM_TEMPLATE:
		frames.add_animation(anim_name)
		frames.set_animation_speed(anim_name,5)
		frames.set_animation_loop(anim_name,true)
		
		var data = ANIM_TEMPLATE[anim_name]
		var anim_frames=[]
		for i in data.frames:
			var frame_rect = Rect2( 
				i * grid_size,  
				data.y_pos * grid_size,  
				grid_size,  
				grid_size  
			) 
			var frame_texture = ImageTexture.create_from_image(image.get_region(frame_rect))  
			frames.add_frame(anim_name,frame_texture)
	frames.remove_animation("default")
	#保存资源
	#var  save_dir = source_file.get_base_dir()
	var save_dir = "res://npc/resources/"
	var filename = "%s/%s.%s"%[save_dir,source_file.get_file().get_basename(),_get_save_extension()]
	print(filename,"导出完成")
	return ResourceSaver.save(frames,filename)
